package com.hs.srm.admin.modules.requisition.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.hs.srm.admin.common.util.StringUtils;
import com.hs.srm.admin.modules.orders.entity.ScmPoHeaderEntity;
import com.hs.srm.admin.modules.orders.entity.ScmPoItemEntity;
import com.hs.srm.admin.modules.orders.service.ScmPoHeaderService;
import com.hs.srm.admin.modules.orders.service.ScmPoItemService;
import com.hs.srm.admin.modules.pricemanagement.entity.HistoricalPriceEntity;
import com.hs.srm.admin.modules.pricemanagement.service.HistoricalPriceService;
import com.hs.srm.admin.modules.pricemanagement.vo.EssentialInformationVO;
import com.hs.srm.admin.modules.requisition.dao.ProPurchRequestHeaderDao;
import com.hs.srm.admin.modules.requisition.entity.ProPurchRequestHeaderEntity;
import com.hs.srm.admin.modules.requisition.entity.ProPurchRequestItemEntity;
import com.hs.srm.admin.modules.requisition.service.ProPurchRequestHeaderService;
import com.hs.srm.admin.modules.requisition.service.ProPurchRequestItemService;
import com.hs.srm.base.common.utils.QueryParam;
import com.hs.srm.common.utils.DateUtils;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sunnykid.text.SunnykidText;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("proPurchRequestHeaderService")
public class ProPurchRequestHeaderServiceImpl extends ServiceImpl<ProPurchRequestHeaderDao, ProPurchRequestHeaderEntity> implements ProPurchRequestHeaderService {

    @Autowired
    private ScmPoHeaderService scmPoHeaderService;

    @Autowired
    private ScmPoItemService scmPoItemService;

    @Autowired
    private ProPurchRequestItemService proPurchRequestItemService;

    @Autowired
    private HistoricalPriceService historicalPriceService;

    //注入DAO
    @Autowired
    private ProPurchRequestHeaderDao proPurchRequestHeaderDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<ProPurchRequestHeaderEntity> page = this.selectHeadPage(
                new QueryParam<ProPurchRequestHeaderEntity>(params).getPage(), new EntityWrapper<ProPurchRequestHeaderEntity>(),
                params);
        return new PageUtils(page);
    }

    private Page<ProPurchRequestHeaderEntity> selectHeadPage(Page<ProPurchRequestHeaderEntity> page,
                                                             Wrapper<ProPurchRequestHeaderEntity> wrapper, Map<String, Object> params) {
        page.setRecords(this.proPurchRequestHeaderDao.selectHeadPage(page, wrapper, params));
        return page;
    }

    @Override
    public ProPurchRequestHeaderEntity queryproPurchRequestHeader() {

        return this.baseMapper.queryProPurchRequestHeader();
    }

    @Override
    public ProPurchRequestHeaderEntity selectById(String pkId) {

        return this.baseMapper.selectById(pkId);
    }

    @Override
    public ProPurchRequestHeaderEntity findByNo(String purchRequestCode) {
        return this.baseMapper.findByNo(purchRequestCode);
    }

    @Override
    public void updateName(ProPurchRequestHeaderEntity proPurchRequestHeaderEntity) {

        this.baseMapper.updateName(proPurchRequestHeaderEntity);
    }

    @Override
    public List<ProPurchRequestHeaderEntity> selectBatchIds(List<String> ids) {

        return this.baseMapper.selectBatchIds(ids);
    }

    //改变货源状态
    @Override
    public boolean changeGoodsStatus(int goodsStatus, String requestCode) {
        ProPurchRequestHeaderEntity headerEntity = new ProPurchRequestHeaderEntity();
        headerEntity.setGoodsStatus(goodsStatus);
        int rows = this.baseMapper.update(headerEntity, new EntityWrapper<ProPurchRequestHeaderEntity>()
                .eq("purch_request_code", requestCode));
        return rows > 0 ? true : false;
    }

    /**
     * 生成订单
     *
     * @param obj
     * @return
     */
    @Override
    public R updateSource(JSONObject obj, String username) {
        //解析json数据
        JSONObject json = JSON.parseObject(obj.toJSONString());
        //从json对象中拿到抬头采购申请号
        ProPurchRequestHeaderEntity proPurchRequestHeader = null;
        ProPurchRequestItemEntity proPurchRequestItemEntity = null;
        //订单数据(目前都先走比价流程)//订单抬头
        ScmPoHeaderEntity scmPoHeaderEntity = new ScmPoHeaderEntity();
        ScmPoItemEntity scmPoItemEntity;
        List<ScmPoItemEntity> ScmPoItemList = new ArrayList<>();
        List<HistoricalPriceEntity> historicalPriceList = new ArrayList<>();
        //采购申请行项目
        List<ProPurchRequestItemEntity> entityList;
        JSONArray itmelist = JSONArray.parseArray(json.getString("essentialInformationVO"));
        //是否来自配额
        String isFromQuota = json.getString("isFromQuota");
        Timestamp date;

        /**************订单号生成*****************/
        //1.查询最大订单号
        String poNo = scmPoHeaderService.selectnum();
        //2.查询最大订单号
        int edition = 0;
        //3.String 转换成int
        int suffix = 0;
        String po_no = "";
        if ("".equals(poNo) || poNo == null) {
            suffix = 0;
            edition = 0;
        } else {
            suffix = Integer.parseInt(poNo.substring(3));
            edition = scmPoHeaderService.getEdition();
        }
        // 看版本号是否和查出来的一至
        if (suffix == edition) {
            for (int i = 0; i < itmelist.size(); i++) {
                JSONObject jo = JSONObject.parseObject(itmelist.getString(i));//EssentialInformationVO
                entityList = new ArrayList<>();
                /****json对象转换成JavaBean*********/
                if (!jo.isEmpty()) {
                    //从配额取值分配货源，每个供应商生成一个订单
                    if (isFromQuota.equals("true") || i == 0) {
                        edition++;
                        suffix++;
                        //订单编号
                        po_no = StringUtils.makeStr("480", suffix, 7).replaceAll(" ", "0");
                    }
                    //订单行项目数据
                    scmPoItemEntity = new ScmPoItemEntity(); //订单行项目
                    JSONObject joo = JSONArray.parseObject(jo.getString("essentialInformationVO"));
                    EssentialInformationVO essentialInformationVO = JSONObject.toJavaObject(joo, EssentialInformationVO.class);
                    //根据剩余配额量判断已用配额,若为零，则已用配额等于配额量；不为零则减去剩余为已用配额
                    if (isFromQuota.equals("true") & essentialInformationVO.getQuantity().compareTo(new BigDecimal(0)) == 0) {
                        //采购订单数量,剩余配额数小于等于申请量,已用配额=配额数
                        scmPoItemEntity.setPoCount(essentialInformationVO.getQuotaNum().subtract(essentialInformationVO.getUsedQuotaNum()));
                        essentialInformationVO.setUsedQuotaNum(essentialInformationVO.getQuotaNum());
                    } else if (isFromQuota.equals("true")) {
                        //采购订单数量,剩余配额数大于申请量，配额-已用-剩余=申请量
                        scmPoItemEntity.setPoCount(essentialInformationVO.getQuotaNum().subtract(essentialInformationVO.getUsedQuotaNum()).subtract(essentialInformationVO.getQuantity()));
                        essentialInformationVO.setUsedQuotaNum(essentialInformationVO.getQuotaNum().subtract(essentialInformationVO.getQuantity()));
                    } else if (isFromQuota.equals("false")) {
                        //采购订单数量,从信息记录取值，不需要判断配额数
                        scmPoItemEntity.setPoCount(essentialInformationVO.getApplyQty());
                    }
                    //是否来自配额，标记
                    if (isFromQuota.equals("true")) {
                        scmPoItemEntity.setFromQuotaFlag("true");
                    } else {
                        scmPoItemEntity.setFromQuotaFlag("false");
                    }
                    scmPoItemEntity.setPrNo(essentialInformationVO.getPurchRequestCode()); //采购申请编码
                    //生成订单行项目号 00010,00020...
                    scmPoItemEntity.setItemNo(String.format("%05d", (i + 1) * 10));
                    //请购行项目号
                    scmPoItemEntity.setPrItemNo(essentialInformationVO.getPurchRequestItemCode());
                    scmPoItemEntity.setSubjectCategory(essentialInformationVO.getSubjectCategory());//科目类别
                    scmPoItemEntity.setMaterialCode(essentialInformationVO.getMaterialCode());//物料号
                    scmPoItemEntity.setMaterialDesc(essentialInformationVO.getMaterialDesc());//物料描述
                    scmPoItemEntity.setFactory(essentialInformationVO.getFactory());//工厂
                    scmPoItemEntity.setStorageLocation(essentialInformationVO.getStorageLocation());//库存地点
                    scmPoItemEntity.setMaterialGroup(essentialInformationVO.getMaterialGroup());//物料组
                    scmPoItemEntity.setRequester(essentialInformationVO.getApplier());//申请者
                    scmPoItemEntity.setInfoCode(essentialInformationVO.getInfoCode());//信息记录编码
                    scmPoItemEntity.setPoUnit(essentialInformationVO.getMeasureUnit()); //采购订单的计量单位
                    scmPoItemEntity.setPoPrice(essentialInformationVO.getPrice()); //含税单价
                    scmPoItemEntity.setPriceUnit(essentialInformationVO.getPriceUnit());
                    scmPoItemEntity.setTaxCode(essentialInformationVO.getTaxCode());//税码
                    //stringToDate
                    scmPoItemEntity.setDeliveryDate(DateUtils.stringToDate(essentialInformationVO.getDeliveryDate(), DateUtils.DATE_PATTERN));//交期
                    scmPoItemEntity.setCostCenter(essentialInformationVO.getCostCenter()); //成本中心
                    scmPoItemEntity.setPoNo(po_no); //这是错的要从新生成多 (自动生成)
                    scmPoItemEntity.setItemUuid(essentialInformationVO.getPkId()); //行项目id
                    scmPoItemEntity.setCreatedBy(username);//创建者
                    //remark
                    scmPoItemEntity.setRemark(essentialInformationVO.getRemark());

                    date = DateUtils.currentTimestamp();
                    scmPoItemEntity.setCreationDate(date);//创建时间
                    //*************记录表******************/
                    //得到抬头id
                    proPurchRequestHeader = this.findByNo(essentialInformationVO.getPurchRequestCode());//通过采购申请编码得到对应的id
                    /*******处理订单抬头****************/
                    scmPoHeaderEntity.setPoId(SunnykidText.getUUID());
                    scmPoHeaderEntity.setPoNo(po_no);
                    scmPoHeaderEntity.setPoType(proPurchRequestHeader.getPurchRequestType());//订单类型
                    //科目类别 ==采购凭证类别
                    scmPoHeaderEntity.setPoCategory(essentialInformationVO.getSubjectCategory()); //采购凭证类别
                    scmPoHeaderEntity.setVendorId(essentialInformationVO.getSapCode()); //以后供应商编码作为供应商的ID
                    //将8001/8002/8003工厂对应公司代码改为8888
                    if (essentialInformationVO.getFactory().equals("8001") || essentialInformationVO.getFactory().equals("8002") || essentialInformationVO.getFactory().equals("8003")) {
                        scmPoHeaderEntity.setCompanyCode("8888");
                    } else {
                        //公司代码
                        scmPoHeaderEntity.setCompanyCode(essentialInformationVO.getFactory());
                    }
                    //采购组
                    scmPoHeaderEntity.setPurchGroup(essentialInformationVO.getPurchGroup());
                    //采购组织， 除1700和1800，其他工厂采购组织1000,1700和1800采购组织1400
                    if (essentialInformationVO.getFactory().equals("1700") || essentialInformationVO.getFactory().equals("1800")) {
                        scmPoHeaderEntity.setPurchOrg("1400");
                    } else {
                        //essentialInformationVO.getPurchOrg()
                        scmPoHeaderEntity.setPurchOrg("1000");
                    }
                    //scmPoHeaderEntity.setPayCondition(essentialInformationVO.getPayTermsPurchase());//付款条件代码
                    scmPoHeaderEntity.setPayCondition(essentialInformationVO.getPayCondition());//付款条件代码
                    scmPoHeaderEntity.setI18nTradeTerms(essentialInformationVO.getI18nTradeTerms());//国际贸易条款
                    scmPoHeaderEntity.setCurrencyCode(essentialInformationVO.getCurrency()); //货币币种
                    scmPoHeaderEntity.setCompanyName(essentialInformationVO.getVendorName());//供应商名称
                    scmPoHeaderEntity.setPoFlag("PRO"); //非生产 pRO  生产 PRO
                    scmPoHeaderEntity.setEdition(edition);//版本控制

                    /**************采购订单行项目*******************/
                    proPurchRequestItemEntity = this.proPurchRequestItemService.selectById(essentialInformationVO.getPkId());

                    proPurchRequestItemEntity.setGoodsStatus(0);
                    entityList.add(proPurchRequestItemEntity);

                    //订单行项目
                    ScmPoItemList.add(scmPoItemEntity);
                    //生产性转换为历史价格
                    if (historicalPriceService.convertToProHistoryPrice(essentialInformationVO) != null) {
                        historicalPriceList.add(historicalPriceService.convertToProHistoryPrice(essentialInformationVO));
                    }

                    //货源分配从配额取则修改配额数
                    if (json.getString("isFromQuota").equals("true")) {
                        boolean res = proPurchRequestItemService.updateQuotaNum(essentialInformationVO);
                    }
                }
                if (proPurchRequestHeader != null && proPurchRequestItemEntity != null) {
                    //货源已指定状态
                    proPurchRequestHeader.setGoodsStatus(0);
                    this.updateName(proPurchRequestHeader);
                    proPurchRequestItemService.updateBatchById(entityList);
                }
                //从配额取值分配货源，每个供应商生成一个订单
                if (isFromQuota.equals("true") || i == 0) {
                    scmPoHeaderService.insertOrUpdate(scmPoHeaderEntity);
                }
            }
            scmPoItemService.insertBatch(ScmPoItemList);
            if (!CollectionUtils.isEmpty(historicalPriceList)) {
                historicalPriceService.insertBatch(historicalPriceList);
            }
        }
        return R.ok().put("poNo", po_no);
    }


}
